<script lang="ts" setup>
import { ref, reactive, onMounted, h, computed, nextTick } from 'vue';
import { 
  Card, Row, Col, Statistic, Button, Input, InputNumber, Space, Form, Select, DatePicker, 
  Table, message, Tag, Tooltip, Modal, Descriptions 
} from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import {
  SvgBellIcon,
  SvgCardIcon,
} from '@vben/icons';
import type { TableColumnsType } from 'ant-design-vue';
import {
  getInvoiceListApi,
  getTenantBillingInfoApi,
  getLandingCompanyOptionsApi,
  getBillingTypeOptionsApi,
  getBillingCategoryOptionsApi,
  getInvoiceStatusOptionsApi,
  getBillingCategoriesListApi,
  saveTenantBillingInfoApi,
  createInvoiceApi,
  downloadInvoiceFileApi,
  type InvoiceApi
} from '#/api/core/invoice';

// 使用API文件中定义的接口类型
type InvoiceRecord = InvoiceApi.InvoiceRecord;

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

// 响应式数据
const loading = ref(false);
const dataSource = ref<InvoiceRecord[]>([]);
const billingInfo = ref<InvoiceApi.TenantBillingInfo | null>(null);
const billingInfoLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  invoice_id: '',
  billing_type: undefined as string | undefined,
  landing_company_id: undefined as number | undefined,
  billing_category: undefined as string | undefined,
  status: undefined as string | undefined,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
});

// 分页数据
const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 选项数据
const landingCompanyOptions = ref<InvoiceApi.LandingCompanyOption[]>([]);
const billingTypeOptions = ref<InvoiceApi.SelectOption[]>([]);
const billingCategoryOptions = ref<InvoiceApi.SelectOption[]>([]);
const statusOptions = ref<InvoiceApi.SelectOption[]>([]);
const optionsLoading = ref(false);

// 详情模态框
const detailVisible = ref(false);
const currentDetail = ref<InvoiceRecord | null>(null);

// 开票类目模态框
const billingCategoriesModalVisible = ref(false);
const billingCategoriesData = ref<Array<{
  company_id: number;
  company_name: string;
  categories: string[];
}>>([]);
const billingCategoriesLoading = ref(false);

// 开票类目表格列定义
const billingCategoriesColumns = [
  {
    title: '落地公司',
    dataIndex: 'company_name',
    key: 'company_name',
    width: 200,
  },
  {
    title: '开票类目',
    dataIndex: 'categories',
    key: 'categories',
  }
];

// 开票信息编辑
const billingModalVisible = ref(false);
const billingSaving = ref(false);
const billingFormRef = ref<FormInstance>();
const billingFormState = reactive({
  invoice_recipient: '',
  invoice_contact_phone: '',
  invoice_mailing_address: '',
});

const invoiceModalVisible = ref(false);
const invoiceSaving = ref(false);
const invoiceFormRef = ref<FormInstance>();
const invoiceFormState = reactive({
  invoice_amount: null as number | null,
  landing_company_id: undefined as number | undefined,
  billing_type: undefined as string | undefined,
  billing_category: undefined as string | undefined,
  related_tasks: '',
  invoice_content: '',
  invoice_remarks: '',
});

// 计算属性：可开票金额统计
const availableAmountDisplay = computed(() => {
  if (!billingInfo.value) return '¥0.00';
  const formatted = billingInfo.value.formatted_invoiceable_amount;
  if (formatted) {
    return `¥${formatted}`;
  }
  const amount = Number(billingInfo.value.invoiceable_amount || 0);
  return `¥${amount.toLocaleString()}`;
});

const availableAmountValue = computed(() => Number(billingInfo.value?.invoiceable_amount || 0));

const formatBillingField = (value?: string | null) => {
  if (value === null || value === undefined) {
    return '—';
  }
  const trimmed = String(value).trim();
  return trimmed.length ? trimmed : '—';
};

const formatRelatedTasks = (value?: string | null) => {
  if (!value) return '';
  try {
    const parsed = JSON.parse(value);
    if (Array.isArray(parsed)) {
      return parsed.join('，');
    }
  } catch (error) {
    // ignore json parse error
  }
  return String(value).split(/\n+/).join('，');
};

const invoiceFormRules = {
  invoice_amount: [
    { required: true, message: '请输入开票金额' },
    {
      validator: (_: unknown, value: number | null) => {
        if (value === null || value === undefined) {
          return Promise.reject('请输入开票金额');
        }
        if (value <= 0) {
          return Promise.reject('开票金额需大于0');
        }
        if (value > availableAmountValue.value) {
          return Promise.reject('开票金额不能超过可开票金额');
        }
        return Promise.resolve();
      },
      trigger: 'change',
    },
  ],
  landing_company_id: [{ required: true, message: '请选择落地公司' }],
  billing_type: [{ required: true, message: '请选择开票类型' }],
  billing_category: [{ required: true, message: '请选择开票类目' }],
};

const resetInvoiceForm = () => {
  invoiceFormState.invoice_amount = null;
  invoiceFormState.landing_company_id = undefined;
  invoiceFormState.billing_type = undefined;
  invoiceFormState.billing_category = undefined;
  invoiceFormState.related_tasks = '';
  invoiceFormState.invoice_content = '劳务服务费';
  invoiceFormState.invoice_remarks = '';
};

const openInvoiceModal = () => {
  if (!billingInfo.value) {
    message.warning('请先配置开票信息');
    return;
  }
  resetInvoiceForm();
  invoiceModalVisible.value = true;
  nextTick(() => invoiceFormRef.value?.clearValidate());
};

const handleInvoiceModalCancel = () => {
  invoiceModalVisible.value = false;
  resetInvoiceForm();
};

const fillInvoiceAmount = () => {
  if (!billingInfo.value) {
    message.warning('请先配置开票信息');
    return;
  }
  invoiceFormState.invoice_amount = Number(availableAmountValue.value.toFixed(2));
};

const submitInvoiceApplication = async () => {
  if (!invoiceFormRef.value) return;
  try {
    await invoiceFormRef.value.validate();
  } catch {
    return;
  }

  if (!invoiceFormState.landing_company_id || !invoiceFormState.billing_type || !invoiceFormState.billing_category) {
    return;
  }

  invoiceSaving.value = true;
  try {
    const amount = Number(Number(invoiceFormState.invoice_amount).toFixed(2));
    await createInvoiceApi({
      landing_company_id: invoiceFormState.landing_company_id,
      invoice_amount: amount,
      billing_type: invoiceFormState.billing_type,
      billing_category: String(invoiceFormState.billing_category),
      invoice_content: invoiceFormState.invoice_content || undefined,
      related_tasks: invoiceFormState.related_tasks || undefined,
      invoice_remarks: invoiceFormState.invoice_remarks || undefined,
    });
    message.success('开票申请已提交');
    invoiceModalVisible.value = false;
    resetInvoiceForm();
    await fetchBillingInfo();
    await fetchData();
  } finally {
    invoiceSaving.value = false;
  }
};

// 表格列定义
const columns: TableColumnsType<InvoiceRecord> = [
  {
    title: '发票ID',
    dataIndex: 'invoice_id',
    key: 'invoice_id',
    width: 130,
    ellipsis: true,
    customRender: ({ record }) => {
      return h(Tooltip, 
        { title: `完整ID: ${record.id}` }, 
        () => record.invoice_id
      );
    }
  },
  {
    title: '落地公司',
    dataIndex: 'landing_company',
    key: 'landing_company',
    width: 150,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.landing_company) {
        return h(Tooltip, 
          { title: record.landing_company.name }, 
          () => record.landing_company!.short_name || record.landing_company!.name
        );
      }
      return '-';
    },
  },
  {
    title: '开票类型',
    dataIndex: 'billing_type_display',
    key: 'billing_type',
    width: 100,
    customRender: ({ record }) => {
      const colorMap = {
        '6_regular': 'blue',
        '6_special': 'green',
        'differential_regular': 'orange'
      };
      return h(Tag, 
        { color: colorMap[record.billing_type] }, 
        () => record.billing_type_display
      );
    }
  },
  {
    title: '开票类目',
    dataIndex: 'billing_category_display',
    key: 'billing_category',
    width: 120,
    ellipsis: true,
  },
  {
    title: '开票金额',
    dataIndex: 'invoice_amount',
    key: 'invoice_amount',
    width: 120,
    align: 'right',
    customRender: ({ text }) => {
      return h('span', 
        { style: { color: '#1890ff', fontWeight: 'bold' } }, 
        `¥${Number(text).toLocaleString()}`
      );
    },
  },
  {
    title: '收票方信息',
    key: 'recipient_info',
    width: 180,
    ellipsis: true,
    customRender: ({ record }) => {
      return h(Tooltip, 
        { title: `${record.invoice_title} | ${record.tax_number}` }, 
        () => record.invoice_title
      );
    },
  },
  {
    title: '关联任务',
    dataIndex: 'related_tasks',
    key: 'related_tasks',
    width: 140,
    ellipsis: true,
    customRender: ({ text }) => {
      const content = formatRelatedTasks(text as string | null | undefined);
      return content
        ? h(Tooltip, { title: content }, () => content)
        : '-';
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap: Record<string, string> = {
        新建: 'default',
        开票中: 'processing',
        已开票: 'success',
        已拒绝: 'error',
        已作废: 'warning',
      };

      return h(
        Tag,
        { color: statusColorMap[record.status] ?? 'default' },
        () => record.status,
      );
    },
  },
  {
    title: '申请时间',
    dataIndex: 'application_time',
    key: 'application_time',
    width: 160,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString('zh-CN');
    },
  },
  {
    title: '快递单号',
    dataIndex: 'express_tracking_number',
    key: 'express_tracking_number',
    width: 140,
    ellipsis: true,
    customRender: ({ text }) => {
      if (text) {
        return h(Tooltip, 
          { title: text }, 
          () => h('span', { style: { color: '#1890ff' } }, [
            h(SvgCardIcon, { style: { marginRight: '4px' } }),
            text.substr(0, 10) + '...'
          ])
        );
      }
      return '-';
    },
  },
  {
    title: '开票备注',
    dataIndex: 'invoice_remarks',
    key: 'invoice_remarks',
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: text }, () => text) : '-';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
    customRender: ({ record }) => {
      const buttons = [
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleViewDetail(record.id),
          },
          () => '查看',
        ),
      ];

      buttons.push(
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            disabled: !record.invoice_file_path,
            onClick: () => handleDownloadInvoice(record),
          },
          () => '下载',
        ),
      );

      return h(Space, { size: 8 }, () => buttons);
    },
  },
];

// 获取租户开票信息
const fetchBillingInfo = async () => {
  try {
    billingInfoLoading.value = true;
    const response = await getTenantBillingInfoApi();
    billingInfo.value = response || null;
    syncBillingForm();
  } catch (error) {
    console.error('❌ 获取开票信息失败:', error);
    billingInfo.value = null;
    syncBillingForm();
  } finally {
    billingInfoLoading.value = false;
  }
};

// 获取所有选项数据
const fetchAllOptions = async () => {
  try {
    optionsLoading.value = true;
    
    const [
      landingCompanyResponse,
      billingTypeResponse,
      billingCategoryResponse,
      statusResponse
    ] = await Promise.all([
      getLandingCompanyOptionsApi(),
      getBillingTypeOptionsApi(),
      getBillingCategoryOptionsApi(),
      getInvoiceStatusOptionsApi()
    ]);
    
    landingCompanyOptions.value = landingCompanyResponse || [];
    billingTypeOptions.value = billingTypeResponse || [];
    billingCategoryOptions.value = billingCategoryResponse || [];
    statusOptions.value = statusResponse || [];
    
  } catch (error) {
    console.error('❌ 获取选项数据失败:', error);
  } finally {
    optionsLoading.value = false;
  }
};

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    const params: InvoiceApi.InvoiceListParams = {
      page: pagination.current,
      per_page: pagination.pageSize,
      invoice_id: searchForm.invoice_id.trim() || undefined,
      billing_type: searchForm.billing_type,
      landing_company_id: searchForm.landing_company_id,
      billing_category: searchForm.billing_category,
      status: searchForm.status,
      start_date: searchForm.start_date,
      end_date: searchForm.end_date,
    };

    const response = await getInvoiceListApi(params);

    dataSource.value = response.data || [];
    pagination.total = response.total || 0;
    pagination.current = response.current_page || 1;
  } catch (error) {
    console.error('❌ 请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    dataSource.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.invoice_id = '';
  searchForm.billing_type = undefined;
  searchForm.landing_company_id = undefined;
  searchForm.billing_category = undefined;
  searchForm.status = undefined;
  searchForm.start_date = undefined;
  searchForm.end_date = undefined;
  pagination.current = 1;
  fetchData();
};

// 导出数据（占位）
const handleExport = () => {
  message.info('导出功能开发中...');
};

// 显示开票类目模态框
const showBillingCategoriesModal = async () => {
  try {
    billingCategoriesLoading.value = true;
    billingCategoriesModalVisible.value = true;

    const response = await getBillingCategoriesListApi();
    billingCategoriesData.value = response || [];
  } catch (error) {
    console.error('获取开票类目失败:', error);
    message.error('获取开票类目失败');
  } finally {
    billingCategoriesLoading.value = false;
  }
};

// 查看详情
const handleViewDetail = (id: string) => {
  const record = dataSource.value.find(item => item.id === id);
  if (record) {
    currentDetail.value = record;
    detailVisible.value = true;
  } else {
    message.error('找不到该记录');
  }
};

const handleDownloadInvoice = async (record: InvoiceRecord) => {
  if (!record.invoice_file_path) {
    message.warning('暂无可下载的发票文件');
    return;
  }
  try {
    const blob = await downloadInvoiceFileApi(record.id);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    const filename = record.invoice_file_path.split('/').pop() || `${record.invoice_number}.pdf`;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('下载发票失败', error);
    message.error('发票下载失败，请稍后重试');
  }
};

// 分页变化处理
const handleTableChange = (paginationParams: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;
  fetchData();
};

// 时间范围选择处理
const handleDateRangeChange = (dates: any, dateStrings: string[]) => {
  searchForm.start_date = dateStrings[0] || undefined;
  searchForm.end_date = dateStrings[1] || undefined;
};

const syncBillingForm = () => {
  billingFormState.invoice_recipient = billingInfo.value?.invoice_recipient ?? '';
  billingFormState.invoice_contact_phone = billingInfo.value?.invoice_contact_phone ?? '';
  billingFormState.invoice_mailing_address = billingInfo.value?.invoice_mailing_address ?? '';
};

// 打开开票信息编辑
const handleConfigBilling = () => {
  syncBillingForm();
  billingFormRef.value?.clearValidate();
  billingModalVisible.value = true;
};

const handleBillingModalCancel = () => {
  billingModalVisible.value = false;
  syncBillingForm();
  billingFormRef.value?.clearValidate();
};

// 保存开票联系信息
const handleSaveBillingInfo = async () => {
  if (!billingFormRef.value) return;
  try {
    await billingFormRef.value.validate();
    billingSaving.value = true;
    const response = await saveTenantBillingInfoApi({
      invoice_recipient: billingFormState.invoice_recipient,
      invoice_contact_phone: billingFormState.invoice_contact_phone,
      invoice_mailing_address: billingFormState.invoice_mailing_address,
    });
    billingInfo.value = response;
    syncBillingForm();
    message.success('开票联系信息已更新');
    billingModalVisible.value = false;
  } catch (error: any) {
    if (error?.errorFields) {
      return;
    }
    console.error('❌ 更新开票联系信息失败:', error);
    message.error('更新开票联系信息失败，请稍后重试');
  } finally {
    billingSaving.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  fetchBillingInfo();
  fetchAllOptions();
  fetchData();
});
</script>

<template>
  <div class="p-5">
    <!-- 顶部卡片区域 -->
    <Row :gutter="16" class="mb-4 summary-row">
      <!-- 可开票金额卡片 -->
      <Col :span="6">
        <Card class="summary-card">
          <Statistic
            title="可开票金额"
            :value="availableAmountDisplay"
            :loading="billingInfoLoading"
            :value-style="{
              color: '#1890ff',
              fontSize: '24px',
              fontWeight: 'bold'
            }"
          />
        </Card>
      </Col>
      
      <!-- 开票信息卡片 -->
      <Col :span="18">
        <Card class="summary-card">
          <div class="flex items-center justify-between">
            <div class="flex-1 pr-4">
              <div class="text-gray-500 mb-2">开票信息</div>
              <template v-if="billingInfoLoading">
                <div class="text-gray-400">加载中...</div>
              </template>
              <template v-else-if="billingInfo">
                <Descriptions :column="3" size="small" colon>
                  <Descriptions.Item label="公司名称">
                    {{ formatBillingField(billingInfo.company_name) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="税务登记号">
                    {{ formatBillingField(billingInfo.tax_registration_number) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="公司地址">
                    {{ formatBillingField(billingInfo.address) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="开户行名称">
                    {{ formatBillingField(billingInfo.bank_name) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="开户行账号" :span="2">
                    {{ formatBillingField(billingInfo.bank_account) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="发票收件人">
                    {{ formatBillingField(billingInfo.invoice_recipient) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="发票事务联系电话">
                    {{ formatBillingField(billingInfo.invoice_contact_phone) }}
                  </Descriptions.Item>
                  <Descriptions.Item label="发票邮寄地址">
                    {{ formatBillingField(billingInfo.invoice_mailing_address) }}
                  </Descriptions.Item>
                </Descriptions>
              </template>
              <template v-else>
                <div class="text-gray-400">未配置开票信息</div>
              </template>
            </div>
            <Button 
              type="primary" 
              :icon="h(SvgBellIcon)"
              :disabled="billingInfoLoading"
              @click="handleConfigBilling"
            >
              {{ billingInfo ? '编辑' : '配置' }}
            </Button>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 主要内容区域 -->
    <Card>
      <!-- 搜索区域 -->
      <div class="mb-4">
        <Form layout="inline" :model="searchForm">
          <Form.Item label="发票ID" name="invoice_id">
            <Input
              v-model:value="searchForm.invoice_id"
              placeholder="请输入发票ID"
              style="width: 160px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item label="开票类型" name="billing_type">
            <Select
              v-model:value="searchForm.billing_type"
              placeholder="请选择开票类型"
              style="width: 140px"
              allowClear
              :loading="optionsLoading"
            >
              <Select.Option 
                v-for="type in billingTypeOptions" 
                :key="type.value" 
                :value="type.value"
              >
                {{ type.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="落地公司" name="landing_company_id">
            <Select
              v-model:value="searchForm.landing_company_id"
              placeholder="请选择落地公司"
              style="width: 160px"
              allowClear
              :loading="optionsLoading"
            >
              <Select.Option 
                v-for="company in landingCompanyOptions" 
                :key="company.value" 
                :value="company.value"
              >
                {{ company.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="开票类目" name="billing_category">
            <Select
              v-model:value="searchForm.billing_category"
              placeholder="请选择开票类目"
              style="width: 140px"
              allowClear
              :loading="optionsLoading"
            >
              <Select.Option 
                v-for="category in billingCategoryOptions" 
                :key="category.value" 
                :value="category.value"
              >
                {{ category.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="开票状态" name="status">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              style="width: 120px"
              allowClear
              :loading="optionsLoading"
            >
              <Select.Option 
                v-for="status in statusOptions" 
                :key="status.value" 
                :value="status.value"
              >
                {{ status.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="申请时间" name="date_range">
            <DatePicker.RangePicker
              style="width: 240px"
              @change="handleDateRangeChange"
            />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                @click="handleSearch"
                :loading="loading"
              >
                查询
              </Button>
              <Button @click="handleReset">
                重置
              </Button>
              <Button @click="handleExport">
                导出数据
              </Button>
              <Button @click="showBillingCategoriesModal">
                查看开票类目
              </Button>
              <Button
                type="primary"
                :disabled="!billingInfo || availableAmountValue <= 0"
                @click="openInvoiceModal"
              >
                开票申请
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      
      <!-- 数据表格 -->
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1800 }"
        @change="handleTableChange"
      />
    </Card>

    <Modal
      v-model:open="billingModalVisible"
      title="编辑开票联系信息"
      :confirm-loading="billingSaving"
      @ok="handleSaveBillingInfo"
      @cancel="handleBillingModalCancel"
    >
      <Form ref="billingFormRef" :model="billingFormState" layout="vertical">
        <Form.Item
          label="发票收件人"
          name="invoice_recipient"
          :rules="[{ required: true, message: '请输入发票收件人' }]"
        >
          <Input
            v-model:value="billingFormState.invoice_recipient"
            placeholder="请输入发票收件人"
          />
        </Form.Item>
        <Form.Item
          label="发票事务联系电话"
          name="invoice_contact_phone"
          :rules="[{ required: true, message: '请输入发票事务联系电话' }]"
        >
          <Input
            v-model:value="billingFormState.invoice_contact_phone"
            placeholder="请输入发票事务联系电话"
          />
        </Form.Item>
        <Form.Item
          label="发票邮寄地址"
          name="invoice_mailing_address"
          :rules="[{ required: true, message: '请输入发票邮寄地址' }]"
        >
          <Input.TextArea
            v-model:value="billingFormState.invoice_mailing_address"
            :rows="3"
            placeholder="请输入发票邮寄地址"
          />
        </Form.Item>
      </Form>
    </Modal>

    <Modal
      v-model:open="invoiceModalVisible"
      title="开票申请"
      :confirm-loading="invoiceSaving"
      @ok="submitInvoiceApplication"
      @cancel="handleInvoiceModalCancel"
      destroy-on-close
    >
      <div class="text-gray-500 mb-3">
        当前可开票金额：<span class="text-primary font-semibold">{{ availableAmountDisplay }}</span>
      </div>
      <Form ref="invoiceFormRef" :model="invoiceFormState" :rules="invoiceFormRules" layout="vertical">
        <Form.Item label="开票金额" name="invoice_amount">
          <Space>
            <InputNumber
              v-model:value="invoiceFormState.invoice_amount"
              :min="0.01"
              :max="availableAmountValue"
              :precision="2"
              style="width: 200px"
              placeholder="请输入开票金额"
            />
            <Button size="small" @click="fillInvoiceAmount">全部金额</Button>
          </Space>
        </Form.Item>
        <Form.Item label="落地公司" name="landing_company_id">
          <Select
            v-model:value="invoiceFormState.landing_company_id"
            placeholder="请选择落地公司"
            allow-clear
          >
            <Select.Option
              v-for="company in landingCompanyOptions"
              :key="company.value"
              :value="company.value"
            >
              {{ company.label }}
            </Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="开票类型" name="billing_type">
          <Select
            v-model:value="invoiceFormState.billing_type"
            placeholder="请选择开票类型"
            allow-clear
          >
            <Select.Option
              v-for="option in billingTypeOptions"
              :key="option.value"
              :value="option.value as string"
            >
              {{ option.label }}
            </Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="开票类目" name="billing_category">
          <Select
            v-model:value="invoiceFormState.billing_category"
            placeholder="请选择开票类目"
            allow-clear
          >
            <Select.Option
              v-for="option in billingCategoryOptions"
              :key="option.value"
              :value="option.value as string"
            >
              {{ option.label }}
            </Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="关联任务" name="related_tasks">
          <Input.TextArea
            v-model:value="invoiceFormState.related_tasks"
            :rows="3"
            placeholder="请输入关联任务信息（可选）"
            show-count
            :maxLength="500"
          />
        </Form.Item>
        <Form.Item label="开票内容" name="invoice_content">
          <Input.TextArea
            v-model:value="invoiceFormState.invoice_content"
            :rows="3"
            placeholder="请输入开票内容（可选）"
            show-count
            :maxLength="500"
          />
        </Form.Item>
        <Form.Item label="备注" name="invoice_remarks">
          <Input.TextArea
            v-model:value="invoiceFormState.invoice_remarks"
            :rows="3"
            placeholder="请输入补充说明（可选）"
            show-count
            :maxLength="500"
          />
        </Form.Item>
      </Form>
    </Modal>

    <!-- 详情模态框 -->
    <Modal
      v-model:open="detailVisible"
      title="发票详情"
      :width="800"
      :footer="null"
    >
      <div v-if="currentDetail">
        <Descriptions :column="2">
          <Descriptions.Item label="发票ID">{{ currentDetail.invoice_id }}</Descriptions.Item>
          <Descriptions.Item label="发票单号">{{ currentDetail.invoice_number }}</Descriptions.Item>
          <Descriptions.Item label="落地公司">
            {{ currentDetail.landing_company?.name || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="开票金额">
            <span style="color: #1890ff; font-weight: bold;">
              ¥{{ Number(currentDetail.invoice_amount).toLocaleString() }}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="开票类型">
            <Tag :color="currentDetail.billing_type === '6_regular' ? 'blue' : 
                         currentDetail.billing_type === '6_special' ? 'green' : 'orange'">
              {{ currentDetail.billing_type_display }}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="开票类目">{{ currentDetail.billing_category_display }}</Descriptions.Item>
          <Descriptions.Item label="发票抬头">{{ currentDetail.invoice_title }}</Descriptions.Item>
          <Descriptions.Item label="税务登记号">{{ currentDetail.tax_number }}</Descriptions.Item>
          <Descriptions.Item label="公司地址" :span="2">{{ currentDetail.company_address || '-' }}</Descriptions.Item>
          <Descriptions.Item label="发票内容" :span="2">{{ currentDetail.invoice_content }}</Descriptions.Item>
          <Descriptions.Item label="关联任务" :span="2">{{ formatRelatedTasks(currentDetail.related_tasks) || '—' }}</Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag :color="currentDetail.status === '开票中' ? 'processing' :
                         currentDetail.status === '已开票' ? 'success' :
                         currentDetail.status === '已拒绝' ? 'error' :
                         currentDetail.status === '已作废' ? 'warning' : 'default'">
              {{ currentDetail.status }}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="申请时间">
            {{ new Date(currentDetail.application_time).toLocaleString('zh-CN') }}
          </Descriptions.Item>
          <Descriptions.Item v-if="currentDetail.express_tracking_number" label="快递单号" :span="2">
            <span style="color: #1890ff;">{{ currentDetail.express_tracking_number }}</span>
          </Descriptions.Item>
          <Descriptions.Item v-if="currentDetail.invoice_remarks" label="开票备注" :span="2">
            {{ currentDetail.invoice_remarks }}
          </Descriptions.Item>
          <Descriptions.Item v-if="currentDetail.rejection_reason" label="拒绝原因" :span="2">
            <span style="color: #ff4d4f;">{{ currentDetail.rejection_reason }}</span>
          </Descriptions.Item>
          <Descriptions.Item label="发票文件" :span="2">
            {{ currentDetail.invoice_file_path || '—' }}
          </Descriptions.Item>
        </Descriptions>
        
      </div>
    </Modal>

    <!-- 开票类目模态框 -->
    <Modal
      v-model:open="billingCategoriesModalVisible"
      title="落地公司开票类目"
      width="800px"
      :footer="null"
    >
      <Table
        :columns="billingCategoriesColumns"
        :dataSource="billingCategoriesData"
        :loading="billingCategoriesLoading"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'categories'">
            <div class="space-y-1">
              <Tag
                v-for="category in record.categories"
                :key="category"
                color="blue"
                class="mb-1"
              >
                {{ category }}
              </Tag>
            </div>
          </template>
        </template>
      </Table>
    </Modal>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-statistic-content {
  font-size: 24px;
}

.summary-row :deep(.ant-col) {
  display: flex;
}

.summary-card {
  width: 100%;
  height: 100%;
}

.text-primary {
  color: #1890ff;
}
</style>
